package com.antdesignbackend.backend.common;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
/**
 * Created by luyangjia on 2020/2/27.
 * 对称加密 des
 * 对称加密 算法主要有 DES、3DES、AES 这里用AES
 */
public class EncryptUtils {
    // 密钥 长度不得小于24
   //  private final static String secretKey = "IBADANBgkqhkiG9w0BAQEFAASCBKgwg";
    // 向量 可有可无 终端后台也要约定

    // 加解密统一使用的编码方式

   // private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";
    /**
     * 加密
     * @param encryptStr 需要加密的字符串
     * @param secretKey 密匙
     * @return
     * @throws Exception
     */
    public static String encrypt(String encryptStr, String secretKey) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES"); //实例化AES密钥生成器
        Cipher cipher = Cipher.getInstance("AES");// 根据AES加密类型实例化加密算法对象
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(secretKey.getBytes(), "AES"));// 根据类型（加密或解密）与密钥初始化加密算法对象
        byte[] b = cipher.doFinal(encryptStr.getBytes(StandardCharsets.UTF_8));//加密算法对象对明文字节数组进行加密
        return Base64.encodeBase64String(b); //加密
    }

    /**
     * 解密
     * @param encryptStr 解密字符串
     * @param secretKey 解密key
     * @return
     * @throws Exception
     */
    public static String decrypt(String encryptStr, String secretKey) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(secretKey.getBytes(), "AES"));
        // 采用base64算法进行转码,避免出现中文乱码
        byte[] encryptBytes = Base64.decodeBase64(encryptStr);
        byte[] decryptBytes = cipher.doFinal(encryptBytes);
        return new String(decryptBytes);
    }
}
